/**
 * @description address router
 * @author boen
 */

const router = require('koa-router')()
const {
    SuccessModel,
    ErrorModel
} = require('../res-model/index')
const {
    createAddress,
    getAddressList,
    getAddressById,
    updateAddressById
} = require('../controller/address')
const loginCheck = require('../middleware/loginCheck')
const Address = require('../models/Address')

// 前缀
router.prefix('/api/user/address')

// 创建收货地址
router.post('/', loginCheck, async (ctx, next) => {
    const userInfo = ctx.session.userInfo // 获取username
    const username = userInfo.username
    const data = ctx.request.body
    try {
        const newAddress = await createAddress(username, data)
        ctx.body = new SuccessModel(newAddress)
    } catch (ex) {
        console.error(ex); 
        ctx.body = new ErrorModel(10004, '创建收货地址失败')
    }
})

// 获取收货地址列表
router.get('/', loginCheck, async (ctx, next) => {
    const userInfo = ctx.session.userInfo // 获取username
    const username = userInfo.username

    const addressList = await getAddressList(username)
    if(addressList) {
        ctx.body = new SuccessModel(addressList)
    }else {
        ctx.body = new ErrorEvent(10005, '查询收货列表失败')
    }
})

// 获取单个收货地址
router.get('/:id', loginCheck, async (ctx, next) => {
    const id = ctx.params.id // 获取动态id
    const address = await getAddressById(id)
    if(address) {
        ctx.body = new SuccessModel(address)
    }else {
        ctx.body = new ErrorEvent(10006, '查询收货地址失败')
    }
})

// 更新收货地址
router.patch('/:id', loginCheck, async (ctx, next) => {
    const id = ctx.params.id
    const data = ctx.request.body
    const username = ctx.session.userInfo.username
    try{
        const newAddress = await updateAddressById(id, username, data)
        ctx.body = new SuccessModel(newAddress)
    }catch(ex) {
        ctx.body = new ErrorModel(10007, '更新收货地址失败')
    }

})

module.exports = router